package com.jrx.anytxn.transaction.service.impl;

import com.jrx.anytxn.common.data.TxnRespCode;
import com.jrx.anytxn.common.exception.TxnBizException;
import com.jrx.anytxn.customer.entity.CmCustomerFirstLevel;
import com.jrx.anytxn.customer.service.ICustomerService;
import com.jrx.anytxn.feign.transaction.request.DealCustBatchReq;
import com.jrx.anytxn.feign.transaction.service.IAnyTxnTransactionService;
import com.jrx.anytxn.i18n.response.TxnRespResult;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.transaction.service.ICustBatchService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

/**
 * 客户日终账务处理实现
 *
 * @author liuyang
 * @date 2020-09-15
 */
@Service
public class CustBatchServiceImpl implements ICustBatchService {

    private static final Logger logger = LoggerFactory.getLogger(CustBatchServiceImpl.class);

    @Autowired
    private IOrganizationTableService organizationTableService;
    @Autowired
    private ICustomerService customerService;
    @Lazy
    @Autowired
    private IAnyTxnTransactionService anyTxnTransactionService;

    /**
     * 客户日终账务处理
     *
     * @param customerId     客户id
     * @param organizationId 机构id
     * @param tenantId       租户id
     * @throws TxnBizException
     * @author liuyang
     * @date 2020-09-15
     */
    @Override
    public void dealCustBatch(String customerId, String organizationId, String tenantId) throws TxnBizException {
        CmCustomerFirstLevel customerFirstLevel = customerService.getFirstLevelByCondition(customerId, organizationId, tenantId);
        PrOrganizationTable organization = organizationTableService.findByOrId(organizationId, tenantId);
        if (!organization.getNextProcessingDate().equals(customerFirstLevel.getNextProcessingDate())) {
            DealCustBatchReq req = new DealCustBatchReq(customerId, organizationId, tenantId);
            TxnRespResult respResult = anyTxnTransactionService.dealCustBatch(req);

            if(null == respResult || 1000 != respResult.getCode()){
                logger.error("客户->{}客户日终账户处理失败", customerId);
                throw new TxnBizException(TxnRespCode.PAYMENT_CUSTOMER_BATCH_ERROR.getCode(),
                        TxnRespCode.PAYMENT_CUSTOMER_BATCH_ERROR.getUserTips());
            }
        }
    }
}
